<template>
  <div class="selectUser">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="Search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false"
            :filter-node-method="filterNode" ref="treeRef" node-key="id" default-expand-all highlight-current
            @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch"
          label-width="68px">
          <el-form-item label="用户名称" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker v-model="dateRange" style="width: 240px" value-format="YYYY-MM-DD" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <div style="text-align: right">
            <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
            <el-button type="primary" size="mini" :disabled="checkedItemList.length === 0"
              @click="submitForm">确定</el-button>
          </div>
        </el-form>

        <el-row class="mb8">
          <el-tag style="margin-right: 10px" v-for="tag in checkedItemList" :key="tag.userId" closable
            @close="handleClose(tag.userId)">{{ tag.userId }}</el-tag>
        </el-row>

        <el-table ref="tableRef" v-loading="loading" :data="userList" @row-click="handleCheck">
          <el-table-column width="50" align="center">
            <template #header v-if="!['转办', '委派'].includes(type)">
              <el-checkbox :indeterminate="checkAllInfo.isIndeterminate" v-model="checkAllInfo.isChecked"
                @change="handleCheckAll"></el-checkbox>
            </template>
            <template #default="{ row }">
              <el-checkbox v-model="row.isChecked" @click.stop @change="() => handleCheck(row)"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="用户编号" align="center" key="userId" prop="userId" v-if="columns[0].visible" />
          <el-table-column label="用户名称" align="center" key="userName" prop="userName" v-if="columns[1].visible"
            :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" v-if="columns[2].visible"
            :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" v-if="columns[3].visible"
            :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" v-if="columns[4].visible"
            width="120" />
          <el-table-column label="状态" align="center" key="status" v-if="columns[5].visible">
            <template #default="scope">
              <el-tag
                :type="scope.row.status === '0' ? '' : 'warning'">{{ scope.row.status === '0' ? '正常' : '停用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[6].visible" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" style="margin-bottom: 35px;" :total="total" :page="queryParams.pageNum"
          :limit="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
  import {
    ref,
    reactive,
    watch,
    onMounted,
    nextTick
  } from 'vue';
  import {
    interactiveTypeSysUser
  } from "@/api/flow/execute";
  import {
    deptTreeSelect
  } from "@/api/system/user";
  import {
    parseTime,
    addDateRange
  } from "@/utils/ruoyi";

  const props = defineProps({
    userVisible: Boolean,
    selectUser: Array,
    postParams: Object,
    type: String
  });

  const emit = defineEmits(['update:userVisible', 'handleUserSelect']);

  // 组件引用
  const treeRef = ref();
  const queryFormRef = ref();
  const tableRef = ref();

  // 数据状态
  const state = reactive({
    // 遮罩层
    loading: true,
    // 显示搜索条件
    showSearch: true,
    // 总条数
    total: 0,
    // 用户表格数据
    userList: [],
    // 部门树选项
    deptOptions: [],
    // 部门名称
    deptName: undefined,
    // 日期范围
    dateRange: [],
    // 查询参数
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      userName: undefined,
      phonenumber: undefined,
      status: "0",
      deptId: undefined
    },
    // 列信息
    columns: [{
        key: 0,
        label: '用户编号',
        visible: true
      },
      {
        key: 1,
        label: '用户名称',
        visible: true
      },
      {
        key: 2,
        label: '用户昵称',
        visible: true
      },
      {
        key: 3,
        label: '部门',
        visible: true
      },
      {
        key: 4,
        label: '手机号码',
        visible: true
      },
      {
        key: 5,
        label: '状态',
        visible: true
      },
      {
        key: 6,
        label: '创建时间',
        visible: true
      }
    ],
    checkedItemList: [], // 已选的itemList
    checkAllInfo: {
      isIndeterminate: false,
      isChecked: false,
    }
  });

  const {
    loading,
    showSearch,
    total,
    userList,
    deptOptions,
    deptName,
    dateRange,
    queryParams,
    columns,
    checkedItemList,
    checkAllInfo
  } = toRefs(state);

  const defaultProps = {
    children: "children",
    label: "label"
  };

  // 初始加载
  onMounted(() => {
    getList();
    getDeptTree();
  });

  // 监听selectUser变化
  watch(() => props.selectUser, (newVal, oldVal) => {
    if (oldVal) {
      nextTick(() => {
        state.checkedItemList = state.checkedItemList.filter(e => {
          let index = newVal ? newVal.findIndex(v => v === e.userId) : -1;
          state.userList.forEach(u => {
            if (u.userId === e.userId) u.isChecked = index !== -1;
          });
          return index !== -1;
        });
      });
    } else if (newVal) {
      state.checkedItemList = newVal.map(e => ({
        userId: e
      }));
    }
  }, {
    deep: true,
    immediate: true
  });

  /** 查询用户列表 */
  const getList = async () => {
    state.loading = true;
    let params = addDateRange(state.queryParams, state.dateRange);

    if (props.type) {
      let postParams = JSON.parse(JSON.stringify(props.postParams));
      delete postParams.url;
      params = {
        ...postParams,
        deptId: state.queryParams.deptId
      };
    }

    try {
      const response = await interactiveTypeSysUser(params);
      state.total = response.total;
      state.userList = response.rows.map(item => ({
        ...item,
        isChecked: state.checkedItemList.some(e => e.userId === item.userId)
      }));
      isCheckedAll();
    } finally {
      state.loading = false;
    }
  };

  /** 查询部门下拉树结构 */
  const getDeptTree = async () => {
    const response = await deptTreeSelect();
    state.deptOptions = response.data;
  };

  // 筛选节点
  const filterNode = (value, data) => {
    if (!value) return true;
    return data.label.includes(value);
  };

  // 节点单击事件
  const handleNodeClick = (data) => {
    state.queryParams.deptId = data.id;
    handleQuery();
  };

  /** 搜索按钮操作 */
  const handleQuery = () => {
    state.queryParams.pageNum = 1;
    getList();
  };

  /** 重置按钮操作 */
  const resetQuery = () => {
    state.dateRange = [];
    queryFormRef.value.resetFields();
    state.queryParams.deptId = undefined;
    treeRef.value.setCurrentKey(null);
    handleQuery();
  };

  // 是否全选中
  const isCheckedAll = () => {
    const len = state.userList.length;
    let count = state.userList.filter(item => item.isChecked).length;
    state.checkAllInfo.isChecked = len === count && len > 0;
    state.checkAllInfo.isIndeterminate = count > 0 && count < len;
  };

  // 全选
  const handleCheckAll = () => {
    const isChecked = state.checkAllInfo.isChecked;
    state.userList = state.userList.map(item => {
      item.isChecked = isChecked;
      return item;
    });

    if (isChecked) {
      // 添加当前页所有用户
      state.userList.forEach(item => {
        if (!state.checkedItemList.some(e => e.userId === item.userId)) {
          state.checkedItemList.push({
            userId: item.userId
          });
        }
      });
    } else {
      // 移除当前页所有用户
      state.userList.forEach(item => {
        const index = state.checkedItemList.findIndex(e => e.userId === item.userId);
        if (index !== -1) {
          state.checkedItemList.splice(index, 1);
        }
      });
    }
  };

  // 单选
  const handleCheck = (row) => {
    // 转办|委派仅支持单选
    if (['转办', '委派'].includes(props.type)) {
      state.userList.forEach(e => {
        e.isChecked = e.userId === row.userId;
      });
      state.checkedItemList = [{
        userId: row.userId
      }];
    } else {
      row.isChecked = !row.isChecked;
      const index = state.checkedItemList.findIndex(n => n.userId === row.userId);

      if (row.isChecked && index === -1) {
        state.checkedItemList.push({
          userId: row.userId
        });
      } else if (!row.isChecked && index !== -1) {
        state.checkedItemList.splice(index, 1);
      }
      isCheckedAll();
    }
  };

  // 删除标签
  const handleClose = (userId) => {
    state.userList.forEach(e => {
      if (e.userId === userId) {
        e.isChecked = false;
      }
    });
    const index = state.checkedItemList.findIndex(n => n.userId === userId);
    if (index !== -1) {
      state.checkedItemList.splice(index, 1);
    }
    isCheckedAll();
  };

  // 取消按钮
  const cancel = () => {
    emit('update:userVisible', false);
  };

  // 提交按钮
  const submitForm = () => {
    emit('handleUserSelect', state.checkedItemList);
    cancel();
  };
</script>